// core/databaseService.js
const cloud = require('wx-server-sdk');
const db = cloud.database();
const _ = db.command;

/**
 * 新增任务记录
 */
async function addTaskRecord(taskRecord) {
  await db.collection('video_tasks').add({ data: taskRecord });
}

/**
 * 更新任务状态、执行结果
 */
async function updateTaskStatus(taskId, status, result = {}, extra = {}) {
  await db.collection('video_tasks').where({ taskId }).update({
    data: {
      status,
      result,
      updatedAt: new Date(),
      ...extra
    }
  });
}

/**
 * 更新任务 executeId/debugURL
 */
async function updateTaskExecuteInfo(taskId, executeId, debugUrl) {
  await db.collection('video_tasks').where({ taskId }).update({
    data: { executeId, debugUrl }
  });
}

/**
 * 查询用户任务（分页）
 */
async function fetchUserTasks(userId, page = 1, limit = 50) {
  const result = await db.collection('video_tasks')
    .where({ userId })
    .orderBy('createdAt', 'desc')
    .skip(0)  // 固定从第一条开始
    .limit(limit)  // 最多返回 limit 条
    .get();
  return result.data || [];
}

/**
 * 查询单个任务
 */
async function fetchTaskById(taskId) {
  const result = await db.collection('video_tasks')
    .where({ taskId })
    .get();
  return result.data[0] || null;
}

/**
 * 查询用户积分
 */
async function fetchUserPointById(userId) {
  const result = await db.collection('users').doc(userId).get();
  return result.data || null;
}


/**
 * 更新用户积分
 */
async function updateUserPoints(userId, amountChange) {
  await db.collection('users').doc(userId).update({
    data: { points: _.inc(amountChange) }
  });
}

/**
 * 记录积分变动历史
 */
async function addPointsHistory(userId, amount, type, reason, taskId) {
  await db.collection('points_history').add({
    data: {
      userId,
      points: amount,
      type,
      reason,
      taskId,
      createTime: new Date()
    }
  });
}

module.exports = {
  addTaskRecord,
  updateTaskStatus,
  updateTaskExecuteInfo,
  fetchUserTasks,
  fetchTaskById,
  fetchUserPointById,
  updateUserPoints,
  addPointsHistory
};
